package com.example.oppotest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.oppotest.entity.xianyu.Clickpost;
import com.example.oppotest.entity.youku.Effpoint;
import com.example.oppotest.entity.youku.youkuCount;
import com.example.oppotest.service.EffpointService;
import com.example.oppotest.util.NetUtils;
import com.example.oppotest.util.TimeConversion;
import com.example.oppotest.util.youku.MapStrUtil;
import com.example.oppotest.util.youku.SignUtil;
import com.example.oppotest.util.youkuUtils;
import org.apache.commons.collections4.map.ListOrderedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wyk
 * @Date: 2025/3/2 11:02
 * 闲鱼广告监测对接文档
 *
 */

@RestController
@RequestMapping("/clickpost")
public class ClickpostController extends BaseController{

    @Autowired
    private EffpointService effpointService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/callback")
    public String callback(@RequestParam String guid,@RequestParam String cid,@RequestParam String CREATIVE01,@RequestParam String eid) throws IOException {
        logger.info("闲鱼回传参数如下：guid:" + guid + "," + "cid:" + cid + "," + "CREATIVE01:" + CREATIVE01 + "," + "eid:" + eid + ",callback");

        Integer ePoint = Integer.parseInt(eid);
        Effpoint effpoint = effpointService.selectEffpointLimit(ePoint);
        if (effpoint == null) {
            logger.info("查无内部有效监控链接:" + ePoint);
            return "查无内部有效监控链接，请联系管理员";
        }
        // 判断转化因子，查看当前时间内优酷记数是否创建，有创建的话数量是否超过转化因子，如果不超过则回转优酷
        Map ykMap = new HashMap();
        ykMap.put("effpointId", effpoint.getId());
        ykMap.put("lid", effpoint.getLid());
        ykMap.put("createTime", TimeConversion.dateToString(new Date()).substring(0, 10)); // 假设2025-03-14
        youkuCount youkuCount = effpointService.selectyoukuCount(ykMap);
        if (youkuCount == null) {
            Map<String, Object> params = new ListOrderedMap<>();
            params.put("event_type", effpoint.getEvent_type());
            params.put("deep_conv", effpoint.getDeep_conv());
            params.put("event_time", TimeConversion.dateToLong());
            params.put("track_id", guid);
            params.put("creative_id", CREATIVE01);
            String content = MapStrUtil.toStr(params);
            String signature = SignUtil.sign(effpoint.getAppKey(), effpoint.getToken(), content); // 签名

            Map<String, Object> sendParams = new ListOrderedMap<>();
            sendParams.put("appKey", effpoint.getAppKey());
            sendParams.put("signature", signature);
            sendParams.put("content", params);

            // 优酷API联调
            String result = NetUtils.postByRaw(youkuUtils.passbackUrl, JSON.toJSONString(sendParams));
            logger.info(effpoint.getId() + "、优酷API回传A1：" + result);
            JSONObject jsonObject = JSONObject.parseObject(result) ;
            if (jsonObject.getString("success").equals("true")) {
                // 联调优酷成功 创建优酷记数
                youkuCount newCount = new youkuCount();
                newCount.setEffpointId(effpoint.getId());
                newCount.setLid(effpoint.getLid());
                newCount.setCreateTime(TimeConversion.dateToString(new Date()).substring(0, 10));
                newCount.setAllNum(1);
                newCount.setFakeNum(1);
                effpointService.insertyoukuCount(newCount);
            }
            return result;
        } else {
            // 如果youkuCount存在，则判断当前总数是否超过转化因子 allNum%100 ，也就是余数
            if (youkuCount.getAllNum() % 100 < effpoint.getTransform()) {
                Map<String, Object> params = new ListOrderedMap<>();
                params.put("event_type", effpoint.getEvent_type());
                params.put("deep_conv", effpoint.getDeep_conv());
                params.put("event_time", TimeConversion.dateToLong());
                params.put("track_id", guid);
                params.put("creative_id", CREATIVE01);
                String content = MapStrUtil.toStr(params);
                String signature = SignUtil.sign(effpoint.getAppKey(), effpoint.getToken(), content); // 签名

                Map<String, Object> sendParams = new ListOrderedMap<>();
                sendParams.put("appKey", effpoint.getAppKey());
                sendParams.put("signature", signature);
                sendParams.put("content", params);

                // 优酷API联调
                String result = NetUtils.postByRaw(youkuUtils.passbackUrl, JSON.toJSONString(sendParams));
                logger.info(effpoint.getId() + "、优酷API回传A2：" + result);
                JSONObject jsonObject = JSONObject.parseObject(result) ;
                if (jsonObject.getString("success").equals("true")) {
                    // 联调优酷成功 更新优酷记数
                    youkuCount updateCount = new youkuCount();
                    updateCount.setEffpointId(youkuCount.getEffpointId());
                    updateCount.setLid(youkuCount.getLid());
                    updateCount.setCreateTime(youkuCount.getCreateTime());
                    updateCount.setAllNum(youkuCount.getAllNum() + 1);
                    updateCount.setFakeNum(youkuCount.getFakeNum() + 1);
                    effpointService.updateyoukuCount(updateCount);
                }
                return result;
            } else {
                // 如果余数大于转化因子则更新总数即可，不用回传
                youkuCount updateCount = new youkuCount();
                updateCount.setEffpointId(youkuCount.getEffpointId());
                updateCount.setLid(youkuCount.getLid());
                updateCount.setCreateTime(youkuCount.getCreateTime());
                updateCount.setAllNum(youkuCount.getAllNum() + 1);
                effpointService.updateyoukuCount(updateCount);
                logger.info("优酷+闲鱼联调数据获取成功,但不回传,余数大于转化因子");
                return "优酷+闲鱼联调数据获取成功,但不回传";
            }
        }
    }

    @GetMapping("/callbackTest")
    public String callbackTest(@RequestParam Map<String, String> params) {
        // 遍历所有参数和值
        logger.info("Params: " + params.toString());
        return "Params: " + params.toString();
    }

}
